package com.heima.gateway.filter;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

/**
 * 认证过滤器，目标是校验token
 */
@Component
//@Order(1)
public class AuthFilter implements GlobalFilter , Ordered {
    /**
     * 执行过滤方法
     * @param exchange  交换机 可以从交换机中获取请求对象和响应对象
     * @param chain 过滤器链
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.判断当前请求是否为登录请求
        URI uri = request.getURI();//包含了host和port以及路径地址
        String path = request.getURI().getPath();//只包含路径地址
        if(path.contains("/login/login_auth")){
            //放行
           return chain.filter(exchange);
        }
    //不是登录请求，设置拦截
        //从请求头对象中获取token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty(token)){
            //表示没有token,则拦截报401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //校验token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if(i==1 || i==2){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }

    /**
     * 当前过滤器执行顺序
     * @return 返回值越小，级别越高，越先执行
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
